/**
 * 
 */
package com.insford.crawling.fifaonline3;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.insford.crawling.fifaonline3.dto.Player;
import com.insford.crawling.fifaonline3.dto.Player.Status;
import com.insford.crawling.fifaonline3.dto.Team;

/**
 * @author 조백규
 *
 */
public class TeamInfoCrawling {

	public static String uri = "http://fifaonline3.inven.co.kr/dataninfo/club/detail.php?code=";
	
	private Log log = LogFactory.getLog(TeamInfoCrawling.class);
	
	private String inputFile = "D:\\DaumCloud\\android\\피파온라인3\\TEAMID.txt";
	
	private String teamFile = "D:\\DaumCloud\\android\\피파온라인3\\TEAM.txt";
	private String playerFile = "D:\\DaumCloud\\android\\피파온라인3\\PLAYER.txt";
	
	private String[] teamIds = null;
	
	private PrintWriter teampw = null;
	private PrintWriter playerpw = null;
	
	public static String seperate = "|";
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		TeamInfoCrawling teamInfo = new TeamInfoCrawling();
		teamInfo.init();
		teamInfo.run();
		teamInfo.close();
	}

	public void init() {
		BufferedReader br = null;
		
		try {
			br = new BufferedReader(new FileReader(inputFile));
			String str = null;
			ArrayList<String> list = new ArrayList<String>();
			while ((str = br.readLine()) != null) {
				list.add(str.trim());
			}
			teamIds = list.toArray(new String[list.size()]);
			
			
			teampw = new PrintWriter(teamFile);
			playerpw = new PrintWriter(playerFile);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		for (int i = 0; i < teamIds.length; i++) {
			String id = teamIds[i];
			
			Team team = this.req(id);
			// 팀ID, 포메이션, 선택가능선수
			teampw.println(id + seperate + team.getFormation() + seperate + team.getSelectplayer() + seperate + team.getFw() + seperate + team.getMf() + seperate + team.getDf() + seperate + team.getStar());
			
			// 팀ID, 선수ID, 상태
			for (Player p : team.getPlayers()) {
				playerpw.println(id + seperate + p.getPlayerid() + seperate + p.getStatus());
			}
			
			
			if (i % 50 == 0) {
				System.out.println(i + " 호출");
			}
		}
	}
	
	public void close() {
		teampw.flush();
		teampw.close();
		
		playerpw.flush();
		playerpw.close();
	}
	

	public Team req(String teamId) {
		
		Team team = new Team();
		
		try {
			
			String result = request(uri + teamId, null);
			result = result.replace("\n", "");
			result = result.replace("\r", "");
			result = result.replace("\t", "");
			
			
			//팀 기본정보
			String pattern = "<DIV class=\"starWrap\"><DIV style=\"width:([0-9]{0,3})px;overflow: hidden;\">.+<div class=\"infoValue\">([0-9]{1,2})&nbsp;.+<div class=\"infoSubject\">포메이션</div><div class=\"infoValue\">(.{5,10})</div>";
			Pattern p = Pattern.compile(pattern);
			Matcher m = p.matcher(result);
			
			if (m.find()) {
				//별표
				String s = m.group(1);
				if (s != null) {
					float f = (Integer.parseInt(s.trim()) + 2) / 20.0f;
					team.setStar(f);
				}
				
				// 선택가능선수
				s = m.group(2);
				if (s != null) {
					team.setSelectplayer(Integer.parseInt(s.trim()));
				}
				
				// 포메이션
				team.setFormation(m.group(3).trim());
			}
			
			//공격수치
			pattern = "<div class=\"score\">([0-9]{1,3})</div>";
			p = Pattern.compile(pattern);
			m = p.matcher(result);
			int i = 0;
			while (m.find()) {
				String score = m.group(1);
				int scoreint = Integer.parseInt(score.trim());
				if (i == 0) {
					team.setFw(scoreint);
				} else if (i == 1) {
					team.setMf(scoreint);
				} else {
					team.setDf(scoreint);
				}
				
				i++;
			}
			
			// 선수리스트
			pattern = "<div class=\"type\"><img src=\"http://img.inven.co.kr/image_2011/fifaonline3/fonticon/icon_36x15_(.{5,8}).png\"></div><div class=\"name\"><a href=\"http://fifaonline3.inven.co.kr/dataninfo/player/detail.php\\?code=([0-9]{8})\">(.{1,20})</a></div>";
			p = Pattern.compile(pattern);
			m = p.matcher(result);
			
			ArrayList<Player> list = new ArrayList<Player>();
			while (m.find()) {
				Player player = new Player();
				
				String pos = m.group(1);
				
				if (pos.equals("starting")) {
					player.setStatus(Status.STARTING);
				} else if (pos.equals("bench")) {
					player.setStatus(Status.BENCH);
				} else if (pos.equals("backup")) {
					player.setStatus(Status.BACKUP);
				}
				
				String s = m.group(2);
				if (s != null) {
					player.setPlayerid(Integer.parseInt(s.trim()));
				}
				list.add(player);
			}
			
			team.setPlayers(list.toArray(new Player[list.size()]));
			
		} catch (Exception e) {
			log.error(null, e);
		}
		
		
		return team;
	}
	
	
	public static String request(String url, String result) {
		
		if (result != null) {
			return result;
		}
		
		try {
			Thread.sleep(50);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		HttpClient client = null;
		HttpGet get = null;
		
		try {
			client = new DefaultHttpClient();
			get = new HttpGet(url);
			HttpResponse response = client.execute(get);
			
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return request(url, result);
	}
}

